package com.example.smart_city_0829.mainFragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.example.smart_city_0829.R;
import com.example.smart_city_0829.activity.LoginActivity;
import com.example.smart_city_0829.activity.waimaidingcan.WaiMaiActivity;
import com.example.smart_city_0829.base.BaseFragment;
import com.example.smart_city_0829.entity.user.User;
import com.example.smart_city_0829.retrofit.NetCallBack;
import com.example.smart_city_0829.utils.Constant;
import com.example.smart_city_0829.utils.SharedPreferencesUtils;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Response;


public class MineFragment extends BaseFragment implements View.OnClickListener {

    private TextView login;
    private ImageView avatar;
    private TextView nikeName;
    private TextView account;
    private TextView userInfo;
    private TextView orderList;
    private TextView changePassword;
    private TextView postAdvise;
    private TextView logout;
    private TextView wmdc;

    public static boolean isLogin = false;
    public static User.UserBean user;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView() {
        login = (TextView) rootView.findViewById(R.id.login);
        avatar = (ImageView) rootView.findViewById(R.id.avatar);
        nikeName = (TextView) rootView.findViewById(R.id.nikeName);
        account = (TextView) rootView.findViewById(R.id.account);
        userInfo = (TextView) rootView.findViewById(R.id.user_info);
        orderList = (TextView) rootView.findViewById(R.id.order_list);
        changePassword = (TextView) rootView.findViewById(R.id.change_password);
        postAdvise = (TextView) rootView.findViewById(R.id.post_advise);
        logout = (TextView) rootView.findViewById(R.id.logout);
        wmdc = rootView.findViewById(R.id.wmdc);
    }

    @Override
    protected void initData() {
        //如果用户登录过就肯定有令牌
        final String token = sharedPreferences.getString("token", "");
        //如果令牌为空（不存在。即未登录状态
        if (TextUtils.isEmpty(token)) {//未登录
            isLogin = false;
            login.setVisibility(View.VISIBLE);
            account.setText("");
            nikeName.setText("暂未登录");
            Glide.with(requireContext())
                    .load(R.mipmap.ic_launcher)
                    .transform(new RoundedCorners(8), new RoundedCorners(8))
                    .into(avatar);
        } else {//已登录
            isLogin = true;
            //隐藏登录按钮
            login.setVisibility(View.GONE);
            final Map<String, ?> all = sharedPreferences.getAll();
            user = gson.fromJson(gson.toJson(all), User.UserBean.class);
            //加载用户头像
            if (user.getAvatar() != null && !TextUtils.isEmpty(user.getAvatar())) {
                Glide.with(requireContext())
                        .load(Constant.BASE_URL + user.getAvatar())
                        .into(avatar);
            }
            //显示用户昵称
            if (user.getNickName() != null && TextUtils.isEmpty(user.getNickName())) {
                nikeName.setText(String.valueOf(user.getNickName()));
            }else{
                nikeName.setText("暂无昵称");
            }
            //显示用户账号
            if (!TextUtils.isEmpty(String.valueOf(user.getUserId()))){
                account.setText(String.valueOf(user.getUserId()));
            }
        }
    }

    @Override
    protected void initEvent() {
        //是否登录按钮不影响
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                migrateTo(LoginActivity.class);
            }
        });
        userInfo.setOnClickListener(this);
        orderList.setOnClickListener(this);
        changePassword.setOnClickListener(this);
        postAdvise.setOnClickListener(this);
        logout.setOnClickListener(this);

        wmdc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                migrateTo(WaiMaiActivity.class);
            }
        });
    }

    //在界面恢复时重新获取用户信息
    @Override
    public void onResume() {
        super.onResume();
        Log.e("MainFragment On Resume", "onResume");
        final String token = sharedPreferences.getString("token", "");
        Log.e("token", token);
        if (token.equals("")) {
            login.setVisibility(View.VISIBLE);
        } else {
            login.setVisibility(View.GONE);
            getUserInfo();
        }
    }

    @Override
    public void onClick(View v) {
        if (isLogin) {
            switch (v.getId()) {
                case R.id.user_info://用户信息

                    break;
                case R.id.order_list://订单列表

                    break;
                case R.id.change_password://更改密码

                    break;
                case R.id.post_advise://意见反馈

                    break;
                case R.id.logout://退出登录
                    editor.clear()
                            .apply();
                    initData();
                    initEvent();
                    break;
            }
        } else {
            showToastShort("请先登录");
        }
    }

    private void getUserInfo() {
        api.getUserInfo().enqueue(new NetCallBack<User>() {
            @Override
            public void onResponse(Call<User> call,@NonNull Response<User> response) {
                final User body = response.body();
                if (body != null && body.getMsg() != null){
                    showToastShort(body.getMsg());
                    if (body.getMsg().contains("成功")) {
                        //存储用户信息
                        user = body.getUser();
                        final Field[] declaredFields = user.getClass().getDeclaredFields();
                        Log.e("UserInfo", ":::::::::");
                        for (Field declaredField : declaredFields) {
                            declaredField.setAccessible(true);
                            final String fieldName = declaredField.getName();
                            try {
                                final String v = String.valueOf(declaredField.get(user));
                                Log.e(fieldName, v);
                                editor.putString(fieldName, v);
                                editor.apply();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                        initData();
                        initEvent();
                    }
                }else {
                    showToastShort("获取用户信息失败");
                }
            }
        });
    }


}